<template>
    <div class="cut">
        <nya-container title="图片裁剪">
            <div class="form-row">
                <div class="custom-file col-md-3">
                    <input
                        ref="input"
                        type="file"
                        name="image"
                        class="form-control"
                        accept="image/*"
                        @change="setImage"
                    />
                </div>
                <div class="form-group col-md-9">
                    <button class="btn btn-outline-primary" @click="zoom(0.2)">放大</button>
                    <button class="btn btn-outline-primary " @click="zoom(-0.2)">缩小</button>
                    <button class="btn btn-outline-primary " @click="move(-10, 0)">左移</button>
                    <button class="btn btn-outline-primary " @click="move(10, 0)">右移</button>
                    <button class="btn btn-outline-primary " @click="move(0, -10)">上移</button>
                    <button class="btn btn-outline-primary " @click="move(0, 10)">下移</button>
                    <button class="btn btn-outline-primary " @click="flipX">左右镜像°</button>
                    <button class="btn btn-outline-primary " @click="flipY">上下镜像°</button>
                </div>
            </div>

            <div class="form-groupp">
                <span class="form-label required"><b>裁剪框</b></span>
                <span class="form-label required">宽(像素)</span>
                <input type="number" class="form-control-sm" v-model="width" @keyup.enter="updateCropperWH"
                       @blur="updateCropperWH"/>
                <span>高(像素)</span>
                <input type="number" class="input form-control-sm" v-model="height" @keyup.enter="updateCropperWH"
                       @blur="updateCropperWH"/>

                <span class="form-label required">旋转度数</span>
                <input type="number" class="form-control-sm" v-model="r">
                <button class="btn btn-outline-primary btn-sm" @click="rotate(-1)">左转{{ r }}°</button>
                <button class="btn btn-outline-primary btn-sm" @click="rotate(1)">右转{{ r }}°</button>
            </div>
            <div class="form-group">
                <button class="btn btn-outline-primary" @click="reset">重置</button>
                <button class="btn btn-outline-danger col-2" @click="cropImage">保存</button>
            </div>


            <div class="content top-padding-1em">
                <section class="cropper-area">
                    <div class="img-cropper">
                        <client-only>
                            <vue-cropper
                                ref="cropper"
                                :aspect-ratio="radio"
                                :src="imgSrc"
                                @zoom="cropMove"
                                @ready="cropMove"
                                @cropmove="cropMove"
                                preview=".preview"
                            />
                        </client-only>
                        <small>
                            原图宽 = {{ this.maxW }} 高 = {{ this.maxH }} <br/>
                            裁剪宽 = {{ this.width }} 高 = {{ this.height }}
                        </small>
                    </div>
                </section>
                <section class="preview-area">
                    <p>预览</p>
                    <div class="preview"/>
                    <p>裁剪结果<small>(右键保存)</small></p>

                    <div class="cropped-image">
                        <img
                            v-if="cropImg"
                            :src="cropImg"
                            alt="裁剪图"
                        />
                        <div v-else class="crop-placeholder"/>
                    </div>
                </section>
            </div>
        </nya-container>

        <nya-foot-info title="Tips">
            <li>图片裁剪功能基于<a href="https://github.com/fengyuanchen/cropperjs" target="_blank">cropperjs</a>实现，请右键保存裁剪后的图片
            </li>
            <li>如果生成时间过长或生成失败，请使用其他浏览器，推荐使用 Chrome</li>
        </nya-foot-info>
    </div>
</template>

<script>
// Local
import VueCropper from 'vue-cropperjs';
import 'cropperjs/dist/cropper.css';

export default {
    name: 'ImageCut',
    head() {
        return this.$store.state.currentTool.head;
    },
    components: {
        VueCropper,
    },
    data() {
        return {
            n: null,
            imgSrc: "",
            cropImg: '',
            data: null,
            containData: null,
            imgData: null,
            width: 960,
            height: 320,
            maxW: 960,
            maxH: 320,
            r: 90,
            radio: NaN,
        };
    },
    methods: {
        init() {
            this.data = this.$refs.cropper.getData();
            this.imgData = this.$refs.cropper.getImageData();
            this.containData = this.$refs.cropper.getContainerData();
            this.maxW = this.imgData.naturalWidth;
            this.maxH = this.imgData.naturalHeight;
            console.log('img', JSON.stringify(this.imgData), "container", JSON.stringify(this.containData));
        },
        updateCropperWH() {
            // 调整裁剪框大小
            try {
                this.init();
                this.width = parseInt(this.width);
                this.height = parseInt(this.height);
                if (this.width > this.maxW) {
                    this.width = this.maxW;
                }
                if (this.height > this.maxH) {
                    this.height = this.maxH;
                }

                this.data.width = this.width;
                this.data.height = this.height;
                this.$refs.cropper.setData(this.data);
            } catch (e) {
                console.log("some error", e);
            }
        },
        cropMove() {
            this.init();
            if (this.data.width !== this.width) {
                this.width = parseInt(this.data.width);
            }
            if (this.data.height !== this.height) {
                this.height = parseInt(this.data.height);
            }

        },
        cropImage() {
            let img = this.$refs.cropper.getCroppedCanvas().toDataURL();
            this.cropImg = img;
            // this.cropImg = URL.createObjectURL(dataURLtoBlob(img));
        },
        flipX() {
            const dom = this.$refs.flipX;
            let scale = dom.getAttribute('data-scale');
            scale = scale ? -scale : -1;
            this.$refs.cropper.scaleX(scale);
            dom.setAttribute('data-scale', scale);
        },
        flipY() {
            const dom = this.$refs.flipY;
            let scale = dom.getAttribute('data-scale');
            scale = scale ? -scale : -1;
            this.$refs.cropper.scaleY(scale);
            dom.setAttribute('data-scale', scale);
        },

        getData() {
            this.data = JSON.stringify(this.$refs.cropper.getData(), null, 4);
        },
        move(offsetX, offsetY) {
            this.$refs.cropper.move(offsetX, offsetY);
        },
        reset() {
            this.$refs.cropper.reset();
            this.r = 90;
            this.init();
            this.cropMove();
        },
        rotate(deg) {
            if (deg > 0) {
                this.$refs.cropper.rotate(parseInt(this.r));
            } else {
                this.$refs.cropper.rotate(0 - parseInt(this.r));
            }
        },
        setImage(e) {
            const file = e.target.files[0];
            if (file.type.indexOf('image/') === -1) {
                this.$noty.success('请选择需要编辑的图片', {timeout: 500});
                return;
            }
            if (typeof FileReader === 'function') {
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.imgSrc = event.target.result;
                    this.$refs.cropper.replace(event.target.result);
                    this.init();
                };
                reader.readAsDataURL(file);
            } else {
                this.$noty.error('文件阅读API权限未开哦~', {timeout: 500});
            }
        },
        zoom(percent) {
            this.$refs.cropper.relativeZoom(percent);
        },
    }
};
</script>

<style lang="scss">

.cut {
    .form-group {
        input {
            border: 1px solid #ced4da;
        }
    }
}


.content {
    display: flex;
    justify-content: space-between;
}

.cropper-area {
    width: 614px;
}

.preview-area {
    width: 307px;
    margin-top: -3rem;
}

.preview-area p {
    font-size: 1.25rem;
    margin: 0;
    margin-bottom: 1rem;
}

.preview-area p:last-of-type {
    margin-top: 1rem;
}

.preview {
    width: 100%;
    height: calc(372px * (9 / 16));
    overflow: hidden;
}

.crop-placeholder {
    width: 100%;
    height: 200px;
    background: #ccc;
}

.cropped-image img {
    max-width: 100%;
}
</style>
